package cn.yunyichina.provider.pay.wechat.common;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by Lullaby on 2016/9/3.
 */
public class XMLUtil {

    public static String buildMapXML(Map<String, String> params) {
        Element xml = DocumentHelper.createElement("xml");
        for (Map.Entry<String, String> entry : params.entrySet()) {
            xml.addElement(entry.getKey()).addCDATA(entry.getValue());
        }
        return xml.asXML();
    }

    public static Map<String, String> xmlToMap(String xml) throws DocumentException {
        Map<String, String> result = new HashMap<>();
        Document doc = DocumentHelper.parseText(xml);
        Element root = doc.getRootElement();
        for (Iterator<Element> iterator = root.elementIterator(); iterator.hasNext(); ) {
            Element e = iterator.next();
            result.put(e.getName(), e.getText());
        }
        return result;
    }

}
